﻿using System;
using System.Windows.Input;

namespace ResourceEnumerator.Inrastructure
{
    public class RelayCommand : ICommand
    {
        #region Fields 

        private readonly Action<object> _execute;
        private readonly Predicate<object> _canExecute;

        private EventHandler _canExecuteEventhandler;

        #endregion

        #region Constructors 

        public RelayCommand(Action<object> execute) : this(execute, null)
        {

        }

        public RelayCommand(Action<object> execute, Predicate<object> canExecute)
        {
            if (execute == null) throw new ArgumentNullException("execute");
            _execute = execute;
            _canExecute = canExecute;
        }

        #endregion

        #region ICommand Members 

        public bool CanExecute(object parameter)
        {
            return _canExecute == null || _canExecute(parameter);
        }

        public event EventHandler CanExecuteChanged
        {
            add
            {
                _canExecuteEventhandler += value;
                CommandManager.RequerySuggested += value;
            }
            remove
            {
                if (_canExecuteEventhandler != null) _canExecuteEventhandler -= value;
                CommandManager.RequerySuggested -= value;
            }
        }

        public void Execute(object parameter)
        {
            _execute(parameter);
        }

        #endregion

        public void RaiseCanExecuteChanged()
        {
            if (_canExecute == null || _canExecuteEventhandler == null)
                return;

            _canExecuteEventhandler(this, EventArgs.Empty);
        }
    }
}
